#!/bin/bash
# copies a bhuman distribution to a robot

usage()
{
  echo "usage: copyfiles [Release|Develop|Debug] [<ipaddress>|(-m n <ipaddress>)*] {options}"
  echo "  options:"
  echo "    -l <location>          set location"
  echo "    -t <color>             set team color to blue, red, yellow, or black"
  echo "    -p <number>            set player number"
  echo "    -n <number>            set team number"
  echo "    -o <port>              overwrite team port"
  echo "    -r                     restart bhuman"
  echo "    -rr                    force restart bhuman and naoqi"
  echo "    -m n <ip>              copy to <ip>, and set playernumber to n (one -m per robot)"
  echo "    -wc                    compile also under Windows"
  echo "    -nc                    never compile"
  echo "    -nr                    do not check whether target is reachable"
  echo "    -d                     remove all log files before copying"
  echo "    -v <percent>           set NAO's volume"
  echo "    -w <profile>           set wireless profile"
  echo "    -h | --help | /h | /?  print this text"
  echo "  examples:"
  echo "    ./copyfiles Develop 192.168.5.14 -p 1"
  echo "    ./copyfiles Release -m 1 10.0.5.14 -m 3 10.0.0.2"
  echo "  NAOqi will be restarted if libbhuman or libgamectrl were changed."
  exit 1
}

copy()
{
  REMOTE=$1
  PLAYER=$2

  if [ ! -z $PLAYER ] && ( (( $PLAYER < 1 )) || (( $PLAYER > 6 )) ); then
    echo "Error: Player number is $PLAYER!"
    exit 1
  fi

  if [ ! -z $CHECK ]; then
    if [ `ping ${pingoptions} $REMOTE >/dev/null && echo 1 || echo 0` = "0" ]; then
      echo "$REMOTE not reachable"
      exit 1
    fi
  fi

  echo "stopping bhuman"
  ssh $sshoptions nao@$REMOTE "/home/nao/bin/bhumand stop > /dev/null"

  if [ ! -z $REMOVE_LOGS ]; then
    echo "removing log files"
    ssh $sshoptions nao@$REMOTE "rm -rf /home/nao/logs/* > /dev/null"
  fi

  echo "updating wireless profiles"
  rsync --del --exclude=.* --exclude=default --chmod=u+rw,go+r,Dugo+x -zrce "ssh $sshoptions" ../../Install/Network/Profiles/. nao@$REMOTE:/home/nao/Profiles
  if [ ! -z $PROFILE ]; then
    RESULT=`ssh $sshoptions nao@$REMOTE "setprofile $PROFILE"`
    if [ -n "$RESULT" ]; then
      if [ "$PROFILE" == "NONE" ] || [ `echo $RESULT | grep -i -c 'no process found'` -eq "1" ]; then
        RESULT=""
      fi
    fi
    if [ ! -z "$RESULT" ]; then
      echo "$RESULT" | grep -v usage >&2
      exit 1
    fi
  fi

  echo "updating bhuman"
  rsync --del --exclude=.* --exclude=/Images --exclude=/Logs --exclude=/Scenes --exclude=/Keys --exclude=libbhuman.so --exclude=libgamectrl.so --chmod=u+rw,go+r,Dugo+x -rzce "ssh $sshoptions" ../../Build/Linux/$COMPONENT/$CONFIG/bhuman ../../Config/. ../../Build/Linux/libgamectrl/$CONFIG/build.cfg nao@$REMOTE:/home/nao/Config

  echo "updating libs"
  RESULT=`rsync --chmod=u+rw,go+r,Dugo+x --stats -zce "ssh $sshoptions" ../../Build/Linux/libbhuman/$CONFIG/libbhuman.so ../../Build/Linux/libgamectrl/$CONFIG/libgamectrl.so nao@$REMOTE:/home/nao/Config`
  if [ `echo "$RESULT" | grep -c 'transferred: 0'` != 1 ]; then
    RESTARTNAOQI=1
  fi

  if [ ! -z $STOPPEDNAOQI ]; then
    echo "starting naoqi"
    ssh $sshoptions nao@$REMOTE "sudo /etc/init.d/naoqi start &> /dev/null"
  elif [ ! -z $RESTARTNAOQI ]; then
    echo "restarting naoqi"
    ssh $sshoptions nao@$REMOTE "sudo /etc/init.d/naoqi restart &> /dev/null"
  fi

  # set volume
  echo "setting volume to $VOLUME%"

  #New naoqi versions use "Master", old use "PCM" as amixer SCONTROL
  ssh $sshoptions nao@$REMOTE "amixer set Master $VOLUME% unmute &> /dev/null"

  # set settings on robot
  if [ ! -z $LOCATION ] || [ ! -z $TEAM ] || [ ! -z $PORT ] || [ ! -z $PLAYER ] || [ ! -z $NUMBER ]; then
    echo "updating settings"
    SEDFLAGS=""
    [ ! -z $LOCATION ] && SEDFLAGS="$SEDFLAGS -e 's/location.*/location = $LOCATION;/'"
    [ ! -z $TEAM ] && SEDFLAGS="$SEDFLAGS -e 's/teamColor.*/teamColor = $TEAM;/'"
    [ ! -z $PLAYER ] && SEDFLAGS="$SEDFLAGS -e 's/playerNumber.*/playerNumber = $PLAYER;/'"
    [ ! -z $NUMBER ] && SEDFLAGS="$SEDFLAGS -e 's/teamNumber.*/teamNumber = $NUMBER;/'"
    [ ! -z $PORT ] && SEDFLAGS="$SEDFLAGS -e 's/teamPort.*/teamPort = $PORT;/'"
    ssh $sshoptions nao@$REMOTE "sed $SEDFLAGS < /home/nao/Config/settings.cfg > /home/nao/Config/settingsTEMP.cfg && mv /home/nao/Config/settingsTEMP.cfg /home/nao/Config/settings.cfg"
  fi

  if [ ! -z $RESTART ]; then
    echo "starting bhuman"
    ssh $sshoptions nao@$REMOTE "/home/nao/bin/bhumand start > /dev/null"
  fi

  true
}

set -e

scriptPath=$(echo $0 | sed "s|^\.\./|`pwd`/../|" | sed "s|^\./|`pwd`/|")
basePath=$(dirname "${scriptPath}")
currPath=$(pwd)
keyFile=../../Config/Keys/id_rsa_nao
sshoptions="-c arcfour -i $keyFile -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=quiet"
if [[ $(uname) == *CYGWIN* ]]; then
  pingoptions="-w 1 -n 1"
elif [ $(uname) == "Darwin" ]; then
  pingoptions="-t 1 -c 1"
else
  pingoptions="-w 1 -c 1"
fi

cd "${basePath}"

# init variables
[ -z $CONFIG ] && CONFIG="Develop"
SOLUTION="B-Human.sln"
COMPONENT="Nao"
PLAYER=
TEAM=
NUMBER=
LOCATION=
REMOTE=
COMPILE=1
CHECK=1
NUMMULTIPLE=0
WINDOWSCOMPILE=
RESTARTNAOQI=
MULTIPLEDATA=
REMOVE_LOGS=
VOLUME=100
PROFILE=
PORT=

# parse options
[ "x" = "x$*" ] && usage
while true; do
  case $1 in
    "")
      break
      ;;
    "-p" | "/p")
      shift
      PLAYER=$1
      ;;
    "-l" | "/l")
      shift
      LOCATION=$1
      ;;
    "-t" | "/t")
      shift
      TEAM=$1
      ;;
    "-n" | "/n")
      shift
      NUMBER=$1
      if [ -z $PORT ]; then
        PORT=`printf "100%02d" $NUMBER`
      fi
      ;;
    "-o" | "/o")
      shift
      PORT=$1
      ;;
    "-wc" | "/wc")
      WINDOWSCOMPILE=1
      ;;
    "-nc" | "/nc")
      COMPILE=
      ;;
    "-r" | "/r")
      RESTART=1
      ;;
    "-rr" | "/rr")
      RESTARTNAOQI=1
      RESTART=1
      ;;
    "-nr" | "/nr")
      CHECK=
      ;;
    "-d" | "/d")
      REMOVE_LOGS=1
      RESTART=1
      ;;
    "-h" | "/h" | "/?" | "--help")
      usage
      ;;
    "-m" | "/m")
      shift
      MULTIPLEDATA[$NUMMULTIPLE]=$1
      shift
      MULTIPLEDATA[$NUMMULTIPLE + 1]=$1
      let "NUMMULTIPLE+=2"
      ;;
    "-v" | "/v")
      shift
      VOLUME=$1
      ;;
    "-w" | "/w")
      shift
      PROFILE=$1
      ;;
    "Nao")
      COMPONENT="Nao"
      ;;
    "Release")
      CONFIG="Release"
      ;;
    "Develop")
      CONFIG="Develop"
      ;;
    "Debug")
      CONFIG="Debug"
      ;;
    -*)
      echo "unknown parameter: $1"
      usage
      ;;
    *)
      REMOTE=$1
      ;;
  esac
  shift
done

#key may only be accessed by the owner. Otherwise ssh will complain
chmod 400 $keyFile

if [ ! -z $COMPILE ]; then
  if [ -z "${ComSpec}${COMSPEC}" ]; then
    # on linux
    make $COMPONENT CONFIG=$CONFIG
    [ $? -ne 0 ] && exit 1
  else
    if [ ! -z $WINDOWSCOMPILE ]; then
      echo "------ Compiling $COMPONENT ($CONFIG) ------"
      DEVENV="$(cygpath -u "$(cygpath -m -s "${VS120COMNTOOLS}")../IDE/devenv.com")"
      CMD="${DEVENV} ../VS2015/${SOLUTION} /Build ${CONFIG} /Project ${COMPONENT}"
      $CMD
      [ $? -ne 0 ] && exit 1
      echo "------ Successfully compiled ------"
    fi
  fi
fi

if [ ! -z $REMOTE ]; then
  copy $REMOTE $PLAYER
else # try to deploy to multiple targets
  if [ "$NUMMULTIPLE" -ne 0 ]; then
    for ((i=0; i < NUMMULTIPLE; i+=2))
    do
      copy ${MULTIPLEDATA[i+1]} ${MULTIPLEDATA[i]} | sed "s%^%[${MULTIPLEDATA[i+1]}] %" &
    done
    wait
  else
    cd "${currPath}"
    exit 1
  fi
fi

cd "${currPath}"
